﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
using System.Data.Sql;
using System.Threading;
using System.IO;
using System.Xml;
using System.Diagnostics;
namespace SearchData
{
    public partial class DataSearch : Form
    {

        private BackgroundWorker m_AsyncWorker;
        private BackgroundWorker m_AsyncWorker1;
        private DateTime begin;
        private DataTable tables;
        private DataTable tables1;
        private DateTime end;
        public string dbName;
        private string serverName;
        private bool isWindowsAuth;
        private string userName;
        private string password;
        private TimeSpan elapsedSpan;
        public delegate void RetrunData();
        private string ConnectionStr = string.Empty;
        private string IncludedTables = string.Empty;
        private System.Windows.Forms.Timer tm = new System.Windows.Forms.Timer();

        public DataSearch()
        {
            InitializeComponent();
            m_AsyncWorker = new BackgroundWorker();
            m_AsyncWorker.WorkerReportsProgress = true;
            m_AsyncWorker.WorkerSupportsCancellation = true;
            m_AsyncWorker.DoWork += new DoWorkEventHandler(m_AsyncWorker_DoWork);
            m_AsyncWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_AsyncWorker_RunWorkerCompleted);

            m_AsyncWorker1 = new BackgroundWorker();
            m_AsyncWorker1.WorkerReportsProgress = true;
            m_AsyncWorker1.WorkerSupportsCancellation = true;
            m_AsyncWorker1.DoWork += new DoWorkEventHandler(m_AsyncWorker_DoWork1);
            m_AsyncWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_AsyncWorker_RunWorkerCompleted1);

            tm.Tick += new EventHandler(tm_Tick);
            ContextMenuStrip mnu = new ContextMenuStrip();
            ToolStripMenuItem mnTableStr = new ToolStripMenuItem("View Table Structure");
            ToolStripMenuItem mnMData = new ToolStripMenuItem("View Matching Data");
            ToolStripMenuItem mnHelp = new ToolStripMenuItem("About");
            mnTableStr.Click += mnTableStr_Click;
            mnMData.Click += mnMData_Click;
            mnHelp.Click += mnHelp_Click;
            mnu.Items.AddRange(new ToolStripItem[] { mnTableStr, mnMData, mnHelp });
            //Assign to datagridview
            grdData.ContextMenuStrip = mnu;

        }

        void mnHelp_Click(object sender, EventArgs e)
        {
            string msg = @"Please visit http://www.blog.dkumar.co.in for detail help";
            MessageBox.Show(msg);
        }

        void mnMData_Click(object sender, EventArgs e)
        {
            string tbname = grdData.Rows[grdData.SelectedCells[0].RowIndex].Cells[0].Value.ToString();
            string colName = grdData.Rows[grdData.SelectedCells[0].RowIndex].Cells[1].Value.ToString();
            if (tbname.Trim().Length <= 0 || colName.Trim().Length <= 0)
            {
                MessageBox.Show("No Data Found.");
            }
            else
            {
                GetTableData(tbname, colName);
            }
        }

        private void GetTableData(string tableName, string columnName)
        {
            string query = "SELECT * FROM " + tableName + " WHERE "+ columnName +" LIKE '%"+ txtData.Text.Trim().Replace("'","''") +"%'" ;
            ShowDetails(query);
        }

        void mnTableStr_Click(object sender, EventArgs e)
        {
            string tbnn = grdData.Rows[grdData.SelectedCells[0].RowIndex].Cells[0].Value.ToString();
            if (tbnn.Trim().Length > 0)
            {
                GetTableStructure(tbnn);
            }
            else
            {
                MessageBox.Show("No Data Exists.");
            }
        }

        private void GetTableStructure(string p)
        {

            try
            {
                string query = "SELECT COLUMN_NAME,DATA_TYPE,ISNULL(IS_NULLABLE,'NULL') IS_NULLABLE,ISNULL(CHARACTER_MAXIMUM_LENGTH,0) CHARACTER_MAXIMUM_LENGTH,ISNULL(CHARACTER_OCTET_LENGTH,0) CHARACTER_OCTET_LENGTH,ISNULL(NUMERIC_PRECISION,0) NUMERIC_PRECISION,ISNULL(NUMERIC_SCALE,0) NUMERIC_SCALE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='" + p + "'";
                ShowDetails(query);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ShowDetails(string p)
        {
            DataSet ds = new DataSet();
            SqlDataAdapter da = null;
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = new SqlConnection(ConnectionStr);
            cmd.CommandTimeout = 0;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = p;
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            ds.Tables[0].TableName = "Aneeta";
            frmShowDetails frm = new frmShowDetails();
            frm.FillGrid(ds);
            frm.Show();
        }

        void m_AsyncWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //prTimer.Value = e.ProgressPercentage;
        }

        public void Shilpa()
        {
            grdData.DataSource = tables;
        }

        public void DK()
        {
            if (lstDatabases.Items.Count > 0)
                this.lstDatabases.Items.Clear();

            if (tables1 != null && tables1.Rows.Count > 0)
            {
                foreach (DataRow row in tables1.Rows)
                    this.lstDatabases.Items.Add(row[0].ToString());
            }
            if (lstDatabases.Items.Count > 0)
                this.lstDatabases.SelectedIndex = 1;

        }

        void m_AsyncWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                end = DateTime.Now;
                tm.Stop();
                if (tables.Rows.Count <= 0)
                    MessageBox.Show("No data found.");

                // prTimer.Visible = false;
                if ((e.Cancelled == true))
                {
                    lblStatus.Text = "Process is cancelled";
                }
                else if (!(e.Error == null))
                {
                    lblStatus.Text = ("Error: " + e.Error.Message);
                }
                else
                {
                    TimeSpan span = new TimeSpan();
                    span = end - begin;
                    lblStatus.ForeColor = Color.Green;
                    lblStatus.Text = "Process Completed. Total Time Taken " + span.TotalSeconds + " seconds";
                }
                grdData.DataSource = tables;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void m_AsyncWorker_DoWork(object sender, DoWorkEventArgs e)
        {

            try
            {
                // BackgroundWorker worker = sender as BackgroundWorker;
                int n = Convert.ToInt32(e.Argument);
                //  prTimer.Value = n;
                //  string dbName = 
                GetDataProcess(m_AsyncWorker, e, dbName);//(n, worker, e);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        void m_AsyncWorker_RunWorkerCompleted1(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                // prTimer.Visible = false;
                if ((e.Cancelled == true))
                {
                    lblStatus.Text = "Process is cancelled";
                }
                else if (!(e.Error == null))
                {
                    lblStatus.Text = ("Error: " + e.Error.Message);
                }
                else
                {

                    RetrunData R = new RetrunData(DK);
                    R.Invoke();
                    lblStatus.Text = "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void m_AsyncWorker_DoWork1(object sender, DoWorkEventArgs e)
        {

            try
            {
                int n = Convert.ToInt32(e.Argument);
                GetDataBase(m_AsyncWorker1, e, tables);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void chkWindowsAuthentication_CheckedChanged(object sender, EventArgs e)
        {

            try
            {
                if (chkWindowsAuthentication.Checked)
                {
                    lblUserId.Visible = false;
                    lblPassword.Visible = false;
                    txtUser.Visible = false;
                    txtPassword.Visible = false;
                }
                else
                {

                    lblUserId.Visible = true;
                    lblPassword.Visible = true;
                    txtUser.Visible = true;
                    txtPassword.Visible = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnGetDataBase_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateData())
                {
                    CreateCredentialFile();
                    lblStatus.Text = "Please while database list is being retrieved!!";
                    lblStatus.ForeColor = Color.Red;
                    this.lstDatabases.Items.Clear();
                    serverName = cmbServerName.Text.Trim();
                    isWindowsAuth = chkWindowsAuthentication.Checked;
                    userName = txtUser.Text.Trim();
                    password = txtPassword.Text.Trim();
                    this.lstDatabases.Text = "Please wait while loading available databases...";
                    DataTable tables = new DataTable("Tables");
                    if (!m_AsyncWorker1.IsBusy)
                    {
                        m_AsyncWorker1.RunWorkerAsync();
                    }

                    //GetDataBase(tables);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetDataBase(BackgroundWorker worker, DoWorkEventArgs e, DataTable tables)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                using (IDbConnection connection = this.GetConnection())
                {
                    tables1 = new DataTable();
                    IDbCommand command = connection.CreateCommand();
                    command.CommandText = "SELECT name FROM sys.Databases ORDER BY name ASC";
                    connection.Open();
                    tables1.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
                }

            }
        }

        private bool ValidateData()
        {
            if (chkWindowsAuthentication.Checked == false && txtUser.Text.Trim().Length > 0 && txtPassword.Text.Trim().Length > 0)
            {
                return true;
            }
            else if (chkWindowsAuthentication.Checked)
            {
                return true;
            }
            MessageBox.Show("If windows authentication is not used then username and password is required");
            return false;
        }

        private IDbConnection GetConnection()
        {
            string str1 = "Integrated Security=true";
            string dbName = "(local)";
            if (serverName.Length > 0)
            {
                dbName = serverName;
            }
            if (!isWindowsAuth)
            {
                str1 = "Integrated Security=false; User Id=" + userName + "; Password=" + password + "; Connection Timeout=1500";
            }
            IDbConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=" + dbName + ";" + str1;
            return con;
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            try
            {
                lblStatus.Text = "";
                begin = DateTime.Now;
                if (IsValidForm() && UserAceeptance() == DialogResult.Yes)
                {
                    IncludedTables = "";
                    IncludedTables = GetIncludedTables();
                    tm.Start();
                    InitiateDataSearch();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private DialogResult UserAceeptance()
        {
            if (rdoAll.Checked)
            {
                string msg = @"If you will select all tables then it might take more time to return the result
depending upon then number of tables in the selected database. 
If you have some idea about the table then you can select the only selected radio button and select multiple tables. 
or chose other options available.
Do you want to proceed with current selection?";
                return MessageBox.Show(msg, "", MessageBoxButtons.YesNo);
            }
            else
            {
                return DialogResult.Yes;
            }
        }

        void tm_Tick(object sender, EventArgs e)
        {
            long elapsedTicks = DateTime.Now.Ticks - begin.Ticks;
            elapsedSpan = new TimeSpan(elapsedTicks);

            lblTimeElapsed.Text = "Time Elapsed : " + elapsedSpan.Minutes.ToString() + "." + elapsedSpan.Seconds.ToString() + " Minutes";


        }

        private string GetIncludedTables()
        {
            StringBuilder sb = new StringBuilder();
            string query = "";
            if ((rdoExclude.Checked || rdoSelected.Checked) && lstTables.SelectedItems.Count <= 0)
            {
                MessageBox.Show("Select atleast one table");
                sb.Append("");
                return "";
            }
            else if (rdoAll.Checked)
            {
                return "";
            }
            else
            {
                foreach (object item in lstTables.SelectedItems)
                {
                    sb.Append("'" + item.ToString() + "',");
                }
                query = sb.ToString().Remove(sb.Length - 1, 1);
                if (rdoSelected.Checked)
                    query = "AND TABLE_NAME IN (" + query + ")";
                else if (rdoExclude.Checked)
                    query = "AND TABLE_NAME NOT IN (" + query + ")";

                return query;
            }

        }

        private bool IsValidForm()
        {
            if (lstDatabases.Text.Trim().Length > 0 && txtData.Text.Trim().Length > 0)
                return true;
            else
            {
                MessageBox.Show("Database Name and Data to Search is required!");
                return false;
            }
        }

        private void InitiateDataSearch()
        {
            if (tables != null && tables.Rows.Count > 0)
                tables.Rows.Clear();
            tables = new DataTable();
            DataRow dr1 = tables.NewRow();
            tables.Columns.Add("Column1");
            tables.Columns.Add("Column2");
            dr1[0] = " ";
            dr1[1] = " ";
            tables.Rows.Add(dr1);
            if (!m_AsyncWorker.IsBusy)
            {
                dbName = lstDatabases.Text.Trim();
                m_AsyncWorker.RunWorkerAsync();
                lblStatus.ForeColor = Color.Red;
                lblStatus.Text = "Wait .. while system is retrieving data!!";
            }
            RetrunData R = new RetrunData(Shilpa);
            R.Invoke();
        }

        private void GetDataProcess(BackgroundWorker worker, DoWorkEventArgs e, string dbName)
        {
            DataSet ds = new DataSet();
            if (worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                tables = new DataTable("Tables");

                DataTable tablestemp = new DataTable();
                tables.Columns.Add("Column1");
                tables.Columns.Add("Column2");
                DataRow dr;
                try
                {

                    SqlDataAdapter da = null;
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = new SqlConnection(ConnectionStr);
                    cmd.CommandTimeout = 0;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = GetQuery();
                    da = new SqlDataAdapter(cmd);
                    da.Fill(ds);

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataTable dt in ds.Tables)
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            dr = tables.NewRow();
                            dr[0] = row[0];
                            dr[1] = row[1];
                            tables.Rows.Add(dr);
                        }
                    }
                }
                else
                {
                    dr = tables.NewRow();
                    dr[0] = " ";
                    dr[1] = " ";
                    tables.Rows.Add(dr);
                }
            }
        }

        private IDbConnection GetConnectionData(string databaseName)
        {
            string str1 = "Integrated Security=true";
            string dbName = "(local)";
            if (cmbServerName.Text.Trim().Length > 0)
            {
                dbName = cmbServerName.Text.Trim();
            }
            if (!chkWindowsAuthentication.Checked)
            {
                str1 = "Integrated Security=false; User Id=" + txtUser.Text.Trim() + "; Password=" + txtPassword.Text.Trim();
            }
            IDbConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=" + dbName + ";" + str1 + "; database=" + databaseName + ";Connection Timeout=0";
            return con;
        }

        private string GetConnectionData(string databaseName, string name)
        {
            string str1 = "Integrated Security=true";
            string dbName = "(local)";
            if (cmbServerName.Text.Trim().Length > 0)
            {
                dbName = cmbServerName.Text.Trim();
            }
            if (!chkWindowsAuthentication.Checked)
            {
                str1 = "Integrated Security=false; User Id=" + txtUser.Text.Trim() + "; Password=" + txtPassword.Text.Trim();
            }

            string ConnectionString = "Data Source=" + dbName + ";" + str1 + "; database=" + databaseName + ";Connection Timeout=0";
            return ConnectionString;
        }

        private void DataSearch_Load(object sender, EventArgs e)
        {
            try
            {
<<<<<<< .mine
                // cmbServerName.Text = System.Net.Dns.GetHostName().Trim() + "\\SQLEXPRESS";
                GetDefaultDatabases();
=======
                // cmbServerName.Text = System.Net.Dns.GetHostName().Trim() + "\\SQLEXPRESS";
                GetDefaultDatabases();

>>>>>>> .r26
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetDefaultDatabases()
        {
            if (File.Exists("Credential.dk"))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load("Credential.dk");
                XmlElement XMLEditNode = xmlDoc.DocumentElement;

                foreach (XmlNode node in XMLEditNode) // Loop through XML file
                {
<<<<<<< .mine
                    cmbServerName.Items.Add(item["ServerAddress"].InnerText);
=======
                    cmbServerName.Items.Add(node["ServerAddress"].InnerText);
>>>>>>> .r26
                }

            }
            else
            {
                cmbServerName.Items.Add(System.Net.Dns.GetHostName().Trim() + "\\SQLEXPRESS");
                cmbServerName.Items.Add(System.Net.Dns.GetHostName().Trim());
            }
        }

        private void CreateCredentialFile()
        {
            if (File.Exists("Credential.dK"))
            {
                UpdateCredential();
            }
            else
            {
                XmlTextWriter writer = new XmlTextWriter("Credential.dk", System.Text.Encoding.UTF8);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;
                writer.WriteStartElement("Servers");
                createNode(cmbServerName.Text, chkWindowsAuthentication.Checked.ToString(), txtUser.Text, txtPassword.Text, writer);
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }

        }

        private void UpdateCredential()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("Credential.dk");
            bool isNodeUpdated = false;
            XmlElement XMLEditNode = xmlDoc.DocumentElement;

            foreach (XmlNode node in XMLEditNode) // Loop through XML file
            {
                if (node["ServerAddress"].InnerText == cmbServerName.Text) // Check for the ID field information
                {
                    node["IsWindowsAuth"].InnerText = chkWindowsAuthentication.Checked.ToString();
                    node["UserId"].InnerText = txtUser.Text.Trim();
                    node["Password"].InnerText = txtPassword.Text.Trim();
                    isNodeUpdated = true;
                }
            }
            if (!isNodeUpdated)
            {
<<<<<<< .mine
                XmlNode node;
                // node = doc.CreateNode(XmlNodeType.Element,"Server",
=======
                XmlElement subRoot = xmlDoc.CreateElement("Server");
                XmlElement appendedElementCode = xmlDoc.CreateElement("ServerAddress");
                XmlText xmlTextCode = xmlDoc.CreateTextNode(cmbServerName.Text);
                appendedElementCode.AppendChild(xmlTextCode);
                subRoot.AppendChild(appendedElementCode);
                xmlDoc.DocumentElement.AppendChild(subRoot);

                XmlElement appendedElementCode1 = xmlDoc.CreateElement("IsWindowsAuth");
                XmlText xmlTextCode1 = xmlDoc.CreateTextNode(chkWindowsAuthentication.Checked.ToString());
                appendedElementCode1.AppendChild(xmlTextCode1);
                subRoot.AppendChild(appendedElementCode1);
                xmlDoc.DocumentElement.AppendChild(subRoot);

                XmlElement appendedElementCode2 = xmlDoc.CreateElement("UserId");
                XmlText xmlTextCode2 = xmlDoc.CreateTextNode(txtUser.Text.Trim());
                appendedElementCode2.AppendChild(xmlTextCode2);
                subRoot.AppendChild(appendedElementCode2);
                xmlDoc.DocumentElement.AppendChild(subRoot);

                XmlElement appendedElementCode3 = xmlDoc.CreateElement("Password");
                XmlText xmlTextCode3 = xmlDoc.CreateTextNode(txtUser.Text.Trim());
                appendedElementCode3.AppendChild(xmlTextCode3);
                subRoot.AppendChild(appendedElementCode3);
                xmlDoc.DocumentElement.AppendChild(subRoot);
>>>>>>> .r26
            }
            xmlDoc.Save("Credential.dk");
        }
        private void createNode(string serveradd, string iswindows, string userid, string password, XmlTextWriter writer)
        {
            writer.WriteStartElement("Server");
            writer.WriteStartElement("ServerAddress");
            writer.WriteString(serveradd);
            writer.WriteEndElement();
            writer.WriteStartElement("IsWindowsAuth");
            writer.WriteString(iswindows);
            writer.WriteEndElement();
            writer.WriteStartElement("UserId");
            writer.WriteString(userid);
            writer.WriteEndElement();
            writer.WriteStartElement("Password");
            writer.WriteString(password);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
        private string GetQuery()
        {
            string query = @"DECLARE @TableName VARCHAR(100) 
                            DECLARE @ColName VARCHAR(100) 
                            DECLARE @Query NVARCHAR(MAX) 
                            DECLARE GetDetails CURSOR FOR 
                            SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE NOT IN ('varbinary','image','xml') {0}
                            OPEN GetDetails 
                            FETCH NEXT FROM GetDetails  
                            INTO @TableName, @ColName   
                            WHILE @@FETCH_STATUS = 0
                            BEGIN  
                                SET @Query = 'IF(( SELECT count(1) FROM  '+@TableName+' WHERE CAST(['+@ColName+'] AS NVARCHAR(MAX)) LIKE ''%{1}%'')>0)'+ 
                                              'SELECT DISTINCT '''+@TableName+''','''+@ColName+''' FROM  '+@TableName+' WHERE CAST(['+@ColName+'] AS NVARCHAR(MAX)) LIKE ''%{1}%''' 
                                EXECUTE SP_EXECUTESQL @Query 
                                FETCH NEXT FROM GetDetails  
                                INTO @TableName, @ColName  
                            END 
                            CLOSE GetDetails; 
                            DEALLOCATE GetDetails; ";

            query = string.Format(query, IncludedTables, txtData.Text.Trim().Replace("'","''"));
            return query;
        }

        private void lstDatabases_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ValidateData())
                {
                    ConnectionStr = GetConnectionData(lstDatabases.Text, "");
                    this.lstTables.Items.Clear();

                    this.lstTables.Text = "Please wait while loading available databases...";
                    //this.ddlDatabases.SelectedIndex = 0;
                    DataTable tables1 = new DataTable("Tables");
                    using (IDbConnection connection = this.GetConnectionData(lstDatabases.Text.Trim()))
                    {
                        IDbCommand command = connection.CreateCommand();
                        command.CommandText = "SELECT name FROM sys.tables WHERE type='U' ORDER BY name ASC";
                        connection.Open();
                        tables1.Load(command.ExecuteReader(CommandBehavior.CloseConnection));
                    }
                    this.lstTables.Items.Clear();
                    foreach (DataRow row in tables1.Rows)
                        this.lstTables.Items.Add(row[0].ToString());

                    //this.lstDatabases.SelectedIndex = 1;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void mnHelp_Click(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string msg = @"DataSearch tool provides flexibility to search data from SQL Server Tables 
and also the data and table structre details.";
            MessageBox.Show(msg);
        }
<<<<<<< .mine

        private void cmbServerName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
=======

        private void cmbServerName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load("Credential.dk");
                XmlElement XMLEditNode = xmlDoc.DocumentElement;

                foreach (XmlNode node in XMLEditNode)
                {
                    if (node["ServerAddress"].InnerText == cmbServerName.Text) // Check for the ID field information
                    {
                        chkWindowsAuthentication.Checked = Convert.ToBoolean(node["IsWindowsAuth"].InnerText);
                        txtUser.Text = node["UserId"].InnerText;
                        txtPassword.Text = node["Password"].InnerText;
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("No details found");
            }
        }

        private void btnRunQuery_Click(object sender, EventArgs e)
        {
            DataSet ds1 = new DataSet();
            try
            {
                if (txtQuery.Text.Trim()!="")
                {
                    SqlDataAdapter da = null;
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = new SqlConnection(ConnectionStr);
                    cmd.CommandTimeout = 0;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = txtQuery.Text.Replace("'", "''");
                    da = new SqlDataAdapter(cmd);
                    da.Fill(ds1);
                    Data frm = new Data();
                    frm.FillGrid(ds1);
                    frm.Show();
                }
                else
                {
                    MessageBox.Show("Query is required");
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tbMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbServerName.Text.Trim().Length>0 && lstDatabases.Text.Trim().Length>0)
            {
                lblServerSettings.Text = " ServerName : " + cmbServerName.Text + " Database Name : " + lstDatabases.Text;

            }
            else
            {
                if(tbMain.SelectedIndex >0)
                MessageBox.Show("Servername and Database Name required to run any query.");

                tbMain.SelectedIndex = 0;
            }
           
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(txtQuery.Text);
            txtQuery.Clear();
        }

        private void btnUndoClear_Click(object sender, EventArgs e)
        {
            txtQuery.Text = Clipboard.GetText();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ProcessStartInfo sInfo = new ProcessStartInfo("http://blog.dkumar.co.in/2013/01/data-search-in-sql-server-tables.html");
            Process.Start(sInfo);
        }

        private void lnkHelp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ProcessStartInfo sInfo = new ProcessStartInfo("http://blog.dkumar.co.in/2013/01/data-search-in-sql-server-tables.html");
            Process.Start(sInfo);
        }

>>>>>>> .r26
    }
}
